package _01_动态数组;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _15_三数之和 {


    //
    public static void main(String[] args) {
        _15_三数之和 v = new _15_三数之和();
        int[] ins = new int[]{-1, 0, 1, 2, -1, -4};
        List<List<Integer>> lists = v.threeSum(ins);
        for (List<Integer> list : lists) {
            System.out.println(list);
        }
    }

    // 固定一个数，然后求剩余两数之和，等于他
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> lists = new ArrayList<>();
        if (nums.length < 3) return lists;
        // 数组排序
        Arrays.sort(nums);
        // 记录上一个数值
        int prev = Integer.MAX_VALUE;
        int end = nums.length - 1;
        for (int i = 0; i < nums.length; i++) {
            if (prev == nums[i]) continue;
            prev = nums[i];
            int left = i + 1;
            int right = end;
            while (left < right) {
                int total = nums[i] + nums[left] + nums[right];
                if (total > 0) {
                    right--;
                } else if (total < 0) {
                    left++;
                } else {
                    // 找到相同值
                    lists.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    // 排除重复的值
                    while (left < right && nums[left] == nums[++left]);
                    while (left < right && nums[right] == nums[--right]);
                }
            }
        }
        return lists;
    }
}
